import Vue from 'vue'
import VueRouter from 'vue-router'
import routes from './routes'
import store from '../store'

Vue.use(VueRouter)

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes,
})

// 权限路由数组
const permissionRoutes = ['/mine', '/confirm']

// 定义全局前置守卫
router.beforeEach((to, from, next) => {
  // to: 即将进入的路由
  // from: 正在离开的路由
  // next: 函数，下一步

  if (permissionRoutes.includes(to.path)) {
    // 需要用户登录后才能访问，判断用户是否登录
    if (store.state.userModule.token) {
      // 有 token 说明用户已登录
      next()
    } else {
      // 没有 token 则说明未登录，跳转到登录页面
      next('/login')
    }
  } else {
    next()
  }
})

export default router
